/**
 * Created by Administrator on 2015/12/17.
 */
"use strict";
var F = require('../../../common/function');
var ware_F = require('./ware_common');
var _o2oServiceApi = require('../../../common/o2oServiceApi');
var o2oServiceApi = new _o2oServiceApi;
var _ = require('underscore');

exports.add_ware = function*(ware, key_validate_array) {
  let error_msg = ware_F.validateFields(ware, key_validate_array);
  if (error_msg != '') {
    return F.returnMsg(400, error_msg, 1);
  }
  ware.act = 1;//后台录入机构
  ware.status = 0;//创建时默认无效，CallBack时将其设为有效
  if (ware.categories && !_.isEmpty(ware.categories)) {
    ware.cateCodes = yield F.array_2_codeArray(ware.categories, 'code');
    delete ware.categories;
  }
  if (ware.shops && !_.isEmpty(ware.shops)) {
    ware.shopids = yield F.array_2_codeArray(ware.shops, 'sid');
    delete ware.shops;
  }
  if (ware.services && !_.isEmpty(ware.services)) {
    ware.serverCodes = yield F.array_2_codeArray(ware.services, 'code');
    delete ware.services;
  }
  //get new ware id
  let new_ware_id = yield o2oServiceApi.post('ware', 'getNextWareId', 1, {act: 1});
  ware.wareid = new_ware_id['result'].id;
  ware.newest = 1;
  ware.auditStatus = 1;//状态 : 1未审核 2审核通过 3审核不通过 4 审核中 ,
  ware.status=0;

  let wareResult = yield o2oServiceApi.post('ware', 'addVersion', 1, ware);
  if (parseInt(wareResult['result']['error']) == 1 || wareResult.status == 400) {
      return F.returnMsg(300, wareResult['message']['msg'], 1);
  } else {
    yield ware_F.generate_img_signature(wareResult['result']);
    let upYunSign = wareResult['result'].upYunSign;
    let obj_ware_update = {act: 1, images: wareResult['result'].images, id: wareResult['result'].id};
    wareResult = yield o2oServiceApi.post('ware', 'updateVersion', 1, obj_ware_update);
    wareResult['result'].upYunSign = upYunSign;

    wareResult['result'] = ware_F.deleteUnuselessFields(wareResult['result']);
    return F.returnMsg(200, '保存成功', 1, wareResult['result']);
  }
};